package com.yeqian.user.handle;

import com.yeqian.entity.ResultJson;
import com.yeqian.user.VO.UserInfoVO;
import com.yeqian.user.entity.LoginConstant;
import com.yeqian.user.service.UserInfoService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录成功处理器
 */
@Component
public class YeqAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserInfoService userInfoService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {

        UserDetails details = (UserDetails) authentication.getPrincipal();
        // 获取用户详细信息
        UserInfoVO userInfoVO = userInfoService.getUserInfoDetailByName(details.getUsername());
        // 每个用户登录，都可以在此处执行自己的一些定时任务
        ResultJson.writeJSON(httpServletResponse, ResultJson.Success(LoginConstant.LOGIN_SUCCESSFUL, userInfoVO));
    }
}
